package com.mq.rabbitmq;

import com.example.myproject.util.JsonUtil;
import com.qiaofang.queue.bean.SendCommunicationData;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

/**
 * Created by Administrator on 2018/7/11.
 */
public class ConsumeZone5 {
    /**
     * 自动应答无线重试，测试加入了新的字段，就得还会有问题吗
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public SimpleMessageListenerContainer messageContainer(ConnectionFactory connectionFactory) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.addQueues(new Queue("sync.zone5.from.apollo"));
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(20);
        container.setConcurrentConsumers(20);
        container.setPrefetchCount(10);


        //不手动确认模式，如果有异常，会重新消费
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
        container.setMessageListener(new ChannelAwareMessageListener() {
            @Override
            public void onMessage(Message message, Channel channel) throws Exception {
                //自动模式，会管这个确认关系吗
                System.out.println("receiver end <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<consume the message " );
                SendCommunicationData data = (SendCommunicationData) SerializationUtils.deserialize(message.getBody());
                if("SYSTEMCONFIG_PROPERTYINDEX_CHANGE".equals(data.getEventType())){
                    System.out.print("data："+JsonUtil.toJson(data));
                    System.out.println("deal start");
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
                }else{
                    System.out.print("data："+JsonUtil.toJson(data)+"<<<<<不处理");
                }
            }
        });
        return container;
    }
}
